﻿/*
 * https://blog.csdn.net/q1295006114/article/details/131583959
 * 分批 加载
 */

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemLoadCilpFPS : MonoBehaviour
{
    //协程id
    private int id;
    //协程字典
    Dictionary<int, Coroutine> dic = new Dictionary<int, Coroutine>();

    /// <summary>
    /// 关闭所有的异步
    /// </summary>
    /// <param name="name"></param>
    public void StopAll()
    {
        StopAllCoroutines();
    }

    /// <summary>
    /// 添加分帧
    /// </summary>
    /// <param name="max">分帧加载的总数量<</param>
    /// <param name="num">一帧调用的帧的数量</param>
    /// <param name="action">具体做什么</param>
    public void AddFPS(int max, int num, Action<int> action)
    {
        int name = id++;
        Coroutine coroutine = StartCoroutine(GetFromInfoList(name, max, num, action));
        dic.Add(name, coroutine);
    }

    /// <summary>
    /// 开始分帧加载
    /// </summary>
    /// <param name="name">协程名称</param>
    /// <param name="max">分帧加载的总数量</param>
    /// <param name="num">一帧调用的帧的数量</param>
    /// <param name="action">具体做什么</param>
    /// <returns></returns>
    IEnumerator GetFromInfoList(int name, int max, int num, Action<int> action)
    {
        for (int i = 0; i < max; i++)
        {
            action(i);
            if (i % num == 0)
            {
                //每一帧提取num条数据
                // Debug.Log("运行时间：" + Time.time + "，创建次数：" + (i + 1));
                yield return null;  // 在下一帧执行
            }
        }
        StopFPS(name);
    }

    /// <summary>
    /// 移除协程
    /// </summary>
    /// <param name="name"></param>
    private void StopFPS(int name)
    {
        if (dic.ContainsKey(name))
        {
            StopCoroutine(dic[name]);
            dic.Remove(name);
        }
    }

}
